package com.sptus.web.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.framework.mqtt.MyMqttClient;
import com.sptus.common.constant.CommonConstant;
import com.sptus.system.domain.Equipment;
import com.sptus.system.domain.model.DevModel;
import com.sptus.system.domain.vo.AppInfo;
import com.sptus.system.service.IDevInfoMsg1Service;
import com.sptus.system.domain.vo.AppDataVo;
import com.sptus.web.config.DataLoaderConfig;
import com.sptus.web.entity.SptUser;
import com.sptus.web.entity.SptUserEquipment;
import com.sptus.web.entity.SptUserParent;
import com.sptus.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/sys/home")
@Api(tags="首页接口")
public class HomeController {
    @Autowired
    private CloudIEquipmentService equipmentService;
    @Autowired
    private ISptUserService sptUserService;

    @Autowired
    private RedisCache redisUtil;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    IDevInfoMsg1Service msg1Service;

    @Autowired
    DataLoaderConfig dataLoaderConfig;

    @Autowired
    ISptUserEquipmentService sptUserEquipmentService;

    @Autowired
    ISptUserParentService sptUserParentService;

    @ApiOperation("设备分类")
    @RequestMapping(value = "/getDevClassify", method = RequestMethod.GET)
    public AjaxResult getDevParameter(AppInfo appInfo, SptUser sptUser, HttpServletRequest request) {

        String header = request.getHeader("version");
        Integer id = sptUser.getId();
        // todo 首页真实数据返回
        if (org.springframework.util.StringUtils.isEmpty(appInfo.getSn())) {
            return AjaxResult.error("please enter sn");
        }
        ArrayList<String> ids = new ArrayList<>();
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,sptUser.getId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(sptUser.getId()+"");

        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,appInfo.getSn());
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);
        SptUserEquipment sptUserEquipment = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);

        if(org.springframework.util.StringUtils.isEmpty(sptUserEquipment)){
            return AjaxResult.error("Please enter correctly sn");
        }

        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());

        List<Equipment> equipments = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);

        try {
            if(ObjectUtil.isEmpty(redisUtil.getCacheObject(CommonConstant.MSG_LOCK_SN + equipments.get(0).getSn()))){
                redisUtil.setCacheObject(CommonConstant.MSG_LOCK_SN + equipments.get(0).getSn(), "1",20, TimeUnit.SECONDS);
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put("FORCE_TRAN","2");
                String jsonString = JSONObject.toJSONString(stringStringHashMap);
                if(!ObjectUtil.isEmpty(equipments.get(0).getMac())){
                    // todo
                    MyMqttClient.publishMessage("/"+equipments.get(0).getMac()+"/Rtesttopic",jsonString,1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        ArrayList<AppDataVo> appDataVos=new ArrayList<>();
        if (StringUtils.isEmpty(header)){
            appDataVos = dataLoaderConfig.loadData(appInfo.getSn(),"old");
        }else {
            appDataVos = dataLoaderConfig.loadData(appInfo.getSn(),"new",sptUser.getId()+"");
        }
        return AjaxResult.success(appDataVos);
    }

    @ApiOperation("地图统计")
    @RequestMapping(value = "/getDevMap", method = RequestMethod.GET)
    public AjaxResult getDevMap(@RequestParam(value = "devType",required = false) String devType) {
        List<Integer> number = new ArrayList<>();
        if (!ObjectUtil.isEmpty(devType)){
            if (devType.equals("3800A")){
                number = Arrays.asList(0,1,2);
            }else if (devType.equals("3800B")){
                number = Arrays.asList(3);
            }else if (devType.equals("3800C")){
                number = Arrays.asList(4);
            }else if (devType.equals("3800D")){
                number = Arrays.asList(5,6);
            }else if (devType.equals("3800E")){
                number = Arrays.asList(7,8);
            }
        }
        ArrayList<HashMap<String, String>> hashMaps =   equipmentService.getDevMap(number);
        return AjaxResult.success(hashMaps);
    }

    @ApiOperation("首页头部")
    @RequestMapping(value = "/getHomeHead", method = RequestMethod.GET)
    public AjaxResult getHomeHead() {
        DevModel devModel = new DevModel();
        List<SptUser> sptUsers = sptUserService.getBaseMapper().selectList(new LambdaQueryWrapper<SptUser>().isNull(SptUser::getDeletedAt));
        ArrayList<HashMap<String, String>> hashMaps =   equipmentService.getHomeHead(devModel);
        HashMap<String, String> users = new HashMap<>();
        users.put("name","Users");
        users.put("num",sptUsers.size()+"");
        hashMaps.add(users);
        return AjaxResult.success(hashMaps);
    }

    @ApiOperation("设备健康值")
    @RequestMapping(value = "/getDevHealth", method = RequestMethod.GET)
    public AjaxResult getDevHealth(DevModel devModel) {
        HashMap<String, Object> hashMaps =   equipmentService.getDevHealth(devModel);
        int allNum = 0;
        if (!ObjectUtil.isEmpty(hashMaps)){
            Set<String> strings = hashMaps.keySet();
            for (String string : strings) {
                allNum += (Integer.parseInt(hashMaps.get(string)+""));
            }

        }else {
            hashMaps=new HashMap<>();
            hashMaps.put("health_num",0);
            hashMaps.put("malfunction",0);
            hashMaps.put("alarm",0);
            hashMaps.put("off_line",0);
        }
        hashMaps.put("health_percent",0);
        hashMaps.put("malfunction_percent",0);
        hashMaps.put("alarm_percent",0);
        hashMaps.put("off_line_percent",25);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("allNum",allNum);
        stringObjectHashMap.put("devInfo",hashMaps);
        return AjaxResult.success(stringObjectHashMap);
    }
    @ApiOperation("设备健康值浮动")
    @RequestMapping(value = "/getDevHealthFloat", method = RequestMethod.GET)
    public AjaxResult getDevHealthFloat(DevModel devModel) {
        ArrayList<HashMap<String, Object>> hashMaps =   equipmentService.getDevHealthFloat(devModel);
        DecimalFormat df = new DecimalFormat("#0.0" ); // 保留一位小数
        for (int i = 0; i < hashMaps.size()-1; i++) {
            int i1 = Integer.parseInt(hashMaps.get(i ).get("health_num").toString()) - Integer.parseInt(hashMaps.get(i+1).get("health_num").toString());
            String format = df.format(i1 / Double.parseDouble(hashMaps.get(i).get("all_num").toString()) * 100);
            hashMaps.get(i ).put("percent",format);
        }
        if (!hashMaps.isEmpty()) {
            hashMaps.remove(hashMaps.size()-1);
        }
        return AjaxResult.success(hashMaps);
    }

    @ApiOperation("设备发电量")
    @RequestMapping(value = "/getDevGeneration", method = RequestMethod.GET)
    public AjaxResult getDevGeneration(DevModel devModel) {
        ArrayList<HashMap<String, String>> hashMaps =   equipmentService.getDevGeneration(devModel);
        return AjaxResult.success(hashMaps);
    }
    @ApiOperation("获得告警列表")
    @RequestMapping(value = "/getDevAlarmList", method = RequestMethod.GET)
    public AjaxResult getDevAlarmList(DevModel devModel) {
        ArrayList<HashMap<String, Object>> hashMaps =   equipmentService.getDevAlarmList(devModel);
        return AjaxResult.success(hashMaps);
    }


}
